'use client' import * as React from 'react' import Link from 'next/link' import { useQuery } from '@tanstack/react-query' import { useT } from '@open-mercato/shared/lib/i18n/context' import { Button } from '@open-mercato/ui/primitives/button' import { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert' import { Textarea } from '@open-mercato/ui/primitives/textarea' import { Label } from '@open-mercato/ui/primitives/label' import { StatusBadge } from '@open-mercato/ui/primitives/status-badge' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@open-mercato/ui/primitives/dialog' import { FieldDiffCard } from '@open-mercato/ui/ai/parts/FieldDiffCard' import type { AiPendingActionCardFieldDiff, AiPendingActionCardRecordDiff, } from '@open-mercato/ui/ai/parts/types' import { ErrorMessage, LoadingMessage, RecordNotFoundState } from '@open-mercato/ui/backend/detail' import { flash } from '@open-mercato/ui/backend/FlashMessages' import { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation' import { apiCall } from '@open-mercato/ui/backend/utils/apiCall' import { OPTIONAL_REQUEST_HEADERS, PENDING_ACTIONS_API_PATH, PENDING_ACTIONS_HREF, formatDateTime, pendingActionChannelLabel, pendingActionErrorMessage, pendingActionStatusLabel, pendingActionStatusVariant, type PendingActionItem, } from '../../../../../components/pending-actions/pendingActionsShared' import { RequesterLabel } from '../../../../../components/pending-actions/RequesterLabel' import { useRequesterLabels } from '../../../../../components/pending-actions/useRequesterLabels' import { refreshPendingActionsNavBadge } from '../../../../../components/pending-actions/pendingActionsNavBadge' export const REJECT_REASON_MAX_LENGTH = 500 type ApiErrorBody = { error?: unknown; code?: unknown } type ConfirmResponse = { ok?: boolean pendingAction?: PendingActionItem mutationResult?: { error?: { code?: unknown; message?: unknown } | null } | null } type DetailLoadResult = | { kind: 'found'; action: PendingActionItem } | { kind: 'not_found' } export class PendingActionRequestError extends Error { readonly status: number readonly code: string | null constructor(status: number, code: string | null) { super(`[internal] Pending action request failed (${status}${code ? `, ${code}` : ''})`) this.name = 'PendingActionRequestError' this.status = status this.code = code } } function readErrorCode(body: unknown): string | null { if (!body || typeof body !== 'object') return null const code = (body as ApiErrorBody).code return typeof code === 'string' && code.length > 0 ? code : null } function actionEndpoint(id: string, suffix?: 'confirm' | 'cancel'): string { const base = `${PENDING_ACTIONS_API_PATH}/${encodeURIComponent(id)}` return suffix ? `${base}/${suffix}` : base } async function loadPendingAction(id: string): Promise { const call = await apiCall(actionEndpoint(id), { headers: OPTIONAL_REQUEST_HEADERS, }) if (call.status === 404 || call.status === 400) return { kind: 'not_found' } if (!call.ok || !call.result) { throw new PendingActionRequestError(call.status, readErrorCode(call.result)) } return { kind: 'found', action: call.result } } async function postDecision( id: string, suffix: 'confirm' | 'cancel', body: Record, ): Promise { const call = await apiCall(actionEndpoint(id, suffix), { method: 'POST', headers: { 'content-type': 'application/json', ...OPTIONAL_REQUEST_HEADERS }, body: JSON.stringify(body), }) if (!call.ok) { throw new PendingActionRequestError(call.status, readErrorCode(call.result)) } return (call.result ?? {}) as TResult } function errorCodeOf(error: unknown): string | null { return error instanceof PendingActionRequestError ? error.code : null } type DetailRowProps = { label: string; children: React.ReactNode } function DetailRow({ label, children }: DetailRowProps) { return (
{label}
{children}
) } type RejectDialogProps = { open: boolean submitting: boolean onOpenChange: (open: boolean) => void onSubmit: (reason: string) => void } export function RejectPendingActionDialog({ open, submitting, onOpenChange, onSubmit }: RejectDialogProps) { const t = useT() const [reason, setReason] = React.useState('') React.useEffect(() => { if (!open) setReason('') }, [open]) const submit = React.useCallback(() => { if (submitting) return onSubmit(reason.trim()) }, [onSubmit, reason, submitting]) const handleKeyDown = React.useCallback( (event: React.KeyboardEvent) => { if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { event.preventDefault() submit() return } if (event.key === 'Escape') { event.preventDefault() onOpenChange(false) } }, [onOpenChange, submit], ) return ( {t('ai_assistant.pendingActions.rejectDialog.title', 'Reject this AI action?')} {t( 'ai_assistant.pendingActions.rejectDialog.description', 'The action will not run. The requester sees the reason you give.', )}